import requests
import json
import time
import argparse
from urllib.parse import quote
import urllib3
from enum import Enum

import requests

from utils.configs import GiteeConfig


class GiteePrPiplineLabel(Enum):
    RUNNING = "gate_running"
    SUCCESS = "gate_pass"
    FAILED = "gate_fail"


class GiteeProcess:
    def __init__(self):
        self.access_token = GiteeConfig.TOKEN
        self.repo_owner = GiteeConfig.REPO_OWNER
        self.repo_name = GiteeConfig.REPO_NAME
        self.headers = {"Content-Type": "application/json",
                        "Authorization": f"token {self.access_token}"}


class GiteePrLabelProcess(GiteeProcess):
    def __init__(self, label_name, pr_id):
        super(GiteePrLabelProcess, self).__init__()
        self.label_name = label_name
        self.pr_id = pr_id

    def get(self):
        url = f"https://gitee.com/api/v5/repos/{self.repo_owner}/{self.repo_name}/pulls/{self.pr_id}/labels"
        response = requests.get(url=url, headers=self.headers, verify=False)
        return response

    def search_existed(self):
        get_response = self.get()
        if get_response.status_code != 200:
            return False
        for label_info in get_response.json():
            if label_info.get("name") == self.label_name:
                return True
        return False

    def add(self):
        url = f"https://gitee.com/api/v5/repos/{self.repo_owner}/{self.repo_name}/pulls/{self.pr_id}/labels"
        if isinstance(self.label_name, list):
            body = self.label_name
        else:
            body = [str(self.label_name)]
        print(f"添加标签: {body}")
        response = requests.post(
            url=url, headers=self.headers, data=json.dumps(body), verify=False)
        print(f"添加标签状态: {response.status_code}, {url}")
        return response

    def delete(self):
        url = f"https://gitee.com/api/v5/repos/{self.repo_owner}/{self.repo_name}/pulls/{self.pr_id}/labels/{quote(self.label_name)}"
        print(f"删除标签: {self.label_name}")
        response = requests.delete(url=url, headers=self.headers, verify=False)
        print(f"删除标签状态: {response.status_code}, {url}")
        return response

    def change(self, new_label):
        print(f"修改标签: {self.label_name} -> {new_label}")
        self.delete()
        GiteePrLabelProcess(new_label, self.pr_id).add()


class GiteePrCommentProcess(GiteeProcess):
    def __init__(self, pr_id):
        super(GiteePrCommentProcess, self).__init__()
        self.pr_id = pr_id

    def add(self, commit_content):
        url = f"https://gitee.com/api/v5/repos/{self.repo_owner}/{self.repo_name}/pulls/{self.pr_id}/comments"
        comment_body = {
            "body": commit_content
        }
        response = requests.post(
            url=url, headers=self.headers, data=json.dumps(comment_body), verify=False)
        print(f"发送评论状态: {response.status_code}, {url}")
        return response
    
    
class GiteePrInfoProcess(GiteeProcess):
    def __init__(self, pr_id):
        super(GiteePrInfoProcess, self).__init__()
        self.pr_id = pr_id

    def get_info(self):
        url = f"{GiteeConfig.URL_ROOT}{self.repo_owner}/{self.repo_name}/pulls/{self.pr_id}"
        print(f"获取pr信息...{url}")
        response = requests.get(url=url, headers=self.headers, verify=False)
        if response.status_code != 200:
            print(f"获取pr信息错误: {response.status_code}")
            return
        return response
    
    @staticmethod
    def get_head_sha(response):
        head_sha = response.json().get("head", {}).get("sha")
        return head_sha
    
    @staticmethod
    def get_pull_request_id(response):
        return response.json().get("id")
    